/**
 * 路由鉴权
*/
//@ts-ignore
import router from "@/router/index.ts";

//引入仓库数据
//@ts-ignore
import useUserStore from "./store/user";

//引入Element-plus
//@ts-ignore
import { ElMessage } from "element-plus";



//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
    const userStore = useUserStore ();
    //获取token判断用户是否登录
    let token  = userStore.userToken; 
    //if token
    if(token){
        //登录了
        if(to.path == '/login'){
            next({path:"/"});
        }else{
            if(userStore.username){
                //放行
                next();
            } else {
                try {
                    await userStore.getUserInfo();  //每次获取用户信息，如果token过期会抛出异常
                    //刷新的时候是异步路由，有可能获取到用户信息，异步路由还没有加载完毕，出现空白
                    //刷新后不能进入这里，动态路由还未生成              
                    next({...to});
                } catch (error) {
                    ElMessage({type:"error",message:"用户身份过期，请重新登录!"});
                    next({path:"/login",query:{redirect:to.path}});  //身份过期，需要重新登录
                }
                //next();  //不判断token是否过期直接放行
            }
        }
    }else{
        //未登录
        if(to.path == '/login'){
            next();
        }else{
            next({path:'/login',query:{redirect:to.path}});
        }
    }
})


//全局后置守卫
router.afterEach((to: any, from: any) => {

})